package com.culture.bootdemo.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

@Slf4j
public class HttpUtils {

    public static JSONObject httpPost(String url, JSONObject jsonParam) throws Exception {
        // post请求返回结果
        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject jsonResult = null;
        HttpPost httpPost = new HttpPost(url);
        // 设置请求和传输超时时间
        httpPost.setConfig(RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build());
        try {
            if (null != jsonParam) {
                // 解决中文乱码问题
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }
            CloseableHttpResponse result = httpClient.execute(httpPost);
            // 请求发送成功，并得到响应
            if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String str = "";
                try {
                    // 读取服务器返回过来的json字符串数据
                    str = EntityUtils.toString(result.getEntity(), "utf-8");
                    // 把json字符串转换成json对象
                    jsonResult = JSONObject.parseObject(str);
                } catch (Exception e) {
                    throw new Exception("post请求提交失败:" + e);
                }
            }
        } catch (IOException e) {
            throw new Exception("post请求提交失败:" + e);
        } finally {
            httpPost.releaseConnection();
        }
        return jsonResult;
    }

    public static JSONObject httpGet(String url, JSONObject jsonParam, Integer timeOut) throws Exception {
        log.info("httpGet jsonParam = {}", jsonParam);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject jsonResult = null;
        if (jsonParam != null) {
            Set<Map.Entry<String, Object>> entries = jsonParam.entrySet();
            StringBuilder sb = new StringBuilder(url);
            sb.append("?");
            for (Map.Entry<String, Object> entry : entries) {
                sb.append(entry.getKey());
                sb.append("=");
                sb.append(entry.getValue());
                sb.append("&");
            }
            url = sb.substring(0, sb.length() - 1);
        }
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(RequestConfig.custom().setSocketTimeout(timeOut == null ? 5000 : timeOut).setConnectTimeout(5000).build());
        try {
            if (null != jsonParam) {
                // 解决中文乱码问题
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
            }
            CloseableHttpResponse result = httpClient.execute(httpGet);
            // 请求发送成功，并得到响应
            if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                try {
                    // 读取服务器返回过来的json字符串数据
                    String str = EntityUtils.toString(result.getEntity(), "utf-8");
                    // 把json字符串转换成json对象
                    jsonResult = JSONObject.parseObject(str);
                } catch (Exception e) {
                    throw new Exception("get请求提交失败:" + e);
                }
            }
        } catch (IOException e) {
            throw new Exception("get请求提交失败:" + e);
        } finally {
            httpGet.releaseConnection();
        }
        log.info("httpGet jsonResult = {}", jsonResult);
        return jsonResult;
    }
}
